const process = require('node:process')
const { SerialPort } = require('serialport')
const Buffer = require('node:buffer').Buffer

const port = new SerialPort({
  path: '/dev/ttyS2',
  baudRate: 115200,
})

const dataToSend = Buffer.from([0x5A, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0xEB, 0xD5])

port.on('open', () => {
  console.log('Serial port opened.')
  port.write(dataToSend, (err) => {
    if (err) {
      return console.log('Error on write: ', err.message)
    }
    console.log('Message sent.')
  })
})

port.on('data', (data) => {
  console.log('Data received:', data)
})

port.on('error', (err) => {
  console.log('Error: ', err.message)
})

console.log('Running serial port test. Press Ctrl+C to exit.')

process.on('SIGINT', () => {
  console.log('Received SIGINT. Exiting...')
  port.close()
  process.exit(0)
})
